package com.faker.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;

@Repository
public class ConnectionOperatorDao {

    @Autowired
    JdbcTemplate jdbcTemplate;

    public List<Map<String, Object>> getTableList() {
        StringBuffer sb = new StringBuffer();
        //TODO 根据 connection.getType()判断数据库类型，执行不同SQL语句
        sb.append(" select table_name as tableName   ");
        sb.append(" from information_schema.tables   ");
        sb.append(" where table_schema = database()  ");
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sb.toString());
        return list;
    }

    public List<Map<String, Object>> getFieldList(String tableName) {
        StringBuffer sb = new StringBuffer();
        //TODO 根据 connection.getType()判断数据库类型，执行不同SQL语句
        sb.append(" select table_name                                                                      as tableName,        ");
        sb.append("        column_name                                                                     as columnName,       ");
        sb.append("        case when is_nullable = 'YES' then 1 else 2 end                                 as isNullable,       ");
        sb.append("        data_type                                                                       as dataType,         ");
        sb.append("        case                                                                                                 ");
        sb.append("            when character_maximum_length is not null then 'char'                                            ");
        sb.append("            else (case when numeric_precision is not null then 'num' else null end) end as lengthType,       ");
        sb.append("        case                                                                                                 ");
        sb.append("            when character_maximum_length is not null then character_maximum_length                          ");
        sb.append("            else numeric_precision end                                                  as length,           ");
        sb.append("        column_comment                                                                  as columnComment     ");
        sb.append(" from information_schema.columns                                                                             ");
        sb.append(" where table_schema = database()                                                                             ");
        sb.append(" and table_name = ?                                                                                          ");
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sb.toString(), tableName);
        return list;
    }


}
